<?php

    class Anketa_m extends Model {

        function Anketa_m () {
            parent::Model();
            $this->load->library('form_validation');             
        }

        public function validate_anketa()
        {
            $first_answer;
            foreach($_POST as $key => $value){
                if(substr($key,0,6)=='answer') {
                    $first_answer = $key; 
                    break;    
                }                   
            }
            $this->form_validation->set_rules('question','pitanje na anketi','required|trim');
            $this->form_validation->set_rules($first_answer,'Molimo unesite najmanje 2 odogovora','checkAnswers');            
            $this->form_validation->set_rules('styleID','styleID','checkStyle');
            $this->form_validation->set_rules('custom_validation','custom_validation','checkPollWidth'); 
            $this->form_validation->set_rules('customstyleid','customstyleid','checkCustomStyle');
            $this->form_validation->set_rules('blockRepeatVotersType','opcije ankete','required');

            $this->form_validation->set_message('required', 'Molimo unesite %s.');
            $this->form_validation->set_message('checkAnswers', 'Molimo unesite najmanje 2 odogovora.');
            $this->form_validation->set_message('checkStyle', 'Molimo odaberite stil ankete.');
            $this->form_validation->set_message('checkPollWidth', 'Molimo odaberite širniu vašeg widget-a.');
            $this->form_validation->set_message('checkCustomStyle', 'Molimo odaberite stil vaše ankete.');

            $this->form_validation->set_error_delimiters('<div class="ValidationErrors">', '</div>');

            return $this->form_validation->run();
        }

        public function createanewpoll()  /* return:TRUE or FALSE */
        {  

            if($this->validate_anketa()){
                /*CHECKBOX ANSWER OPTIONS*/
                $multipleselection = 0;
                $ownanswer = 0;
                $randomize = 0;

                if(isset($_POST['multipleChoice'])){
                    $multipleselection = 1;
                }
                if(isset($_POST['randomiseAnswers'])){
                    $randomize = 1;
                }
                if(isset($_POST['otherAnswer'])){
                    $ownanswer = 1;
                }


                /*STYLES OPTIONS*/
                $styleid = '---';
                $stylecustomid = 0;
                $widgetsize = 0;            

                if($_POST['customstyleid']!=0){
                    $stylecustomid = $_POST['customstyleid'];
                }else{
                    $styleid =$_POST['styleID'];
                    $widgetsize = $_POST['poll_width'];
                }

                $account_total_votes = 0;
                switch ($this->session->userdata('acounttype_id')){
                    case 1:     $account_total_votes = 100;         break;     
                    case 2:     $account_total_votes = 1000;        break;     
                    case 3:     $account_total_votes = 4294967295;  break;     
                    case 4:     $account_total_votes = 4294967295;  break;     
                }

                /*CREATE A POLL*/
                $poll = array(
                'question' => $_POST['question'],
                'multipleselection' => $multipleselection,
                'ownanswer' => $ownanswer,
                'randomize' => $randomize,
                'account_id' => $this->session->userdata('id'),
                'style_id' => $styleid,
                'stylecustom_id' => $stylecustomid,
                'widgetsize' => $widgetsize,
                'foto_path' => $_POST['_foto'],
                'status' => 1,
                'votes_left' => $account_total_votes                
                );

                $this->db->insert('poll', $poll);  
                $pollid = $this->db->insert_id();


                /*CREATE A ANSWERS*/            
                $questions = array();
                foreach($_POST as $key => $value){
                    if(substr($key,0,6)=='answer'){
                        $questions[]=$value;   
                    }                
                }
                $i=1;
                foreach($questions as $value){
                    if($value!='Ostavi prazno da bi obrisao odgovor'){
                        $answer = array(
                        'text' => $value,
                        'position' => $i,
                        'poll_id' => $pollid,

                        );
                        $this->db->insert('answer', $answer); 
                        $i++;
                    }
                }


                /*POLL OPTIONS*/
                $options = array(
                'poll_id' => $pollid,            
                'pollrepeatvoters_id' => $_POST['blockRepeatVotersType']
                );

                $this->db->insert('polloptions', $options);  


                return 1;
            }else{
                return FALSE;
            }
        }

        public function listaj_ankete(){
            return $this->db->get_where('poll', array('account_id'=> $this->session->userdata('id'),'status !='=>0))->result();
        }

        public function editpoll()
        {
            if($this->validate_anketa()){
                /*CHECKBOX ANSWER OPTIONS*/
                $multipleselection = 0;
                $ownanswer = 0;
                $randomize = 0;

                if(isset($_POST['multipleChoice'])){
                    $multipleselection = 1;
                }
                if(isset($_POST['randomiseAnswers'])){
                    $randomize = 1;
                }
                if(isset($_POST['otherAnswer'])){
                    $ownanswer = 1;
                }


                /*STYLES OPTIONS*/ 
                $styleid = '---';
                $stylecustomid = 0;
                $widgetsize = 0;            

                if($_POST['customstyleid']!=0){
                    $stylecustomid = $_POST['customstyleid'];
                }else{
                    $styleid =$_POST['styleID'];
                    $widgetsize = $_POST['poll_width']; 
                }

                /*EDIT POLL*/
                $poll = array(
                'question' => $_POST['question'],
                'multipleselection' => $multipleselection,
                'ownanswer' => $ownanswer,
                'randomize' => $randomize,
                'account_id' => $this->session->userdata('id'),
                'style_id' => $styleid,
                'stylecustom_id' => $stylecustomid,
                'widgetsize' => $widgetsize,
                'foto_path' => $_POST['_foto'],
                );

                $this->db->where('id', $_POST['poll_id'])->update('poll', $poll); 

                /*CREATE A ANSWERS*/            
                $questions = array();
                $questions_id = array();
                foreach($_POST as $key => $value){
                    if(substr($key,0,6)=='answer'){
                        $questions_id[]=substr($key,7, strlen($key));
                        $questions[]=$value;
                    }                
                };

                for($i=1; $i<=count($questions);$i++){
                    if($questions[$i-1]!='Ostavi prazno da bi obrisao odgovor'){

                        //return false; 
                        $answer = array(
                        'text' => $questions[$i-1],
                        'position' => $i,
                        'poll_id' => $_POST['poll_id']
                        );
                        if($this->check_if_anser_exist($questions_id[$i-1], $_POST['poll_id'])){
                            $this->db->where('id', $questions_id[$i-1])->update('answer', $answer);    //UPDATE ANSWER IF EXIST                       
                        }else{
                            $this->db->insert('answer', $answer);                                      //INSERT ANSEER
                        }
                    }
                };    

                /*POLL OPTIONS*/ 
                $options = array(
                'poll_id' => $_POST['poll_id'],            
                'pollrepeatvoters_id' => $_POST['blockRepeatVotersType']
                );       

                $this->db->where('poll_id', $_POST['poll_id'])->update('polloptions', $options);    

                return 1;
            }else{
                return FALSE;
            }
        }

        public function check_if_anser_exist($id,$pollid){

            // Check if a record exists for this SKU
            $this->db->from('answer');
            $this->db->where(array('id'=>$id));
            $this->db->where(array('poll_id'=>$pollid));

            if ($this->db->count_all_results() == 0) {  
                return FALSE;
            }else{
                return TRUE;
            }
        }

        public function deleteanswer($id){
            if($this->db->delete('answer', array('id' => $id))){
                return true;
            }else return false;
        }

        public function citaj_anketu($id=NULL){ /* return:object (title, description, keywords) */
            if($id!=NULL){
                if(isset($_GET['id'])){
                    $id=$_GET['id'];
                }  
            }
            return $this->db->get_where('poll', array('id'=> $id))->result();
        }

        public function citaj_odgovore($id=NULL){ /* return:object (title, description, keywords) */
            if($id!=NULL){
                if(isset($_GET['id'])){
                    $id=$_GET['id'];
                }  
            }
            return $this->db->order_by('position', 'asc')->get_where('answer', array('poll_id'=> $id))->result();
        }

        public function citaj_opcije($id=NULL){ /* return:object (title, description, keywords) */
            if($id!=NULL){
                if(isset($_GET['id'])){
                    $id=$_GET['id'];
                }  
            }
            return $this->db->get_where('polloptions', array('poll_id'=> $id))->result();
        }

        public function readstyles(){ /* return:object (title, description, keywords) */
            return $this->db->order_by('id', 'asc')->get_where('style')->result();
        }

        public function readstyles_custom(){ /* return:object (title, description, keywords) */
            //return $this->db->order_by('id', 'asc')->get_where('style')->result();
            return $this->db->order_by('id', 'asc')->get_where('stylecustom', array('account_id'=> $this->session->userdata('id')))->result();
        }

        public function glasaj($type){ /* return: true or false - WRITE VOTE TO DATABASE */

            $poll_over_limit = $this->db->get_where('poll', array('id'=> $_GET['poll_id']))->result();
            $limit = $poll_over_limit[0]->votes_left;
            if($limit==0){
                echo $_GET['jsoncall'] . '(' . json_encode( array('result'=> false, 'reason' => 'Prekoračen limit makimalnog broja glasanja za anketu!') ) . ');'; 
                return;
            }else{
                switch ($type){
                    case 'radio': //RADIO VOTE

                        $own_answer_text = NULL ;
                        if($_GET['own_anser']){
                            if($_GET['answerid']==0){
                                $own_answer_text = $_GET['own_answer_text'];    
                            }                
                        }
                        $votes = array (
                        'poll_id'=>$_GET['poll_id'],
                        'answer_id'=>$_GET['answerid'],
                        'own_answer_text'=>$own_answer_text
                        );
                        if($this->vote_radio_checkbox($votes)){
                            echo $_GET['jsoncall'] . '(' . json_encode( array('result'=> true) ) . ');';
                        }else{
                            echo $_GET['jsoncall'] . '(' . json_encode( array('result'=> false) ) . ');';
                        }
                        break;
                    case 'checkbox': //CHECKBOX VOTE                    

                        $anwers = $_GET['answerid'];
                        $success;
                        foreach($anwers as $id){

                            $own_answer_text = NULL ;
                            if($_GET['own_anser']){
                                if($id==0){
                                    $own_answer_text = $_GET['own_answer_text'];    
                                }                
                            }
                            $votes = array (
                            'poll_id'=>$_GET['poll_id'],
                            'answer_id'=>$id,
                            'own_answer_text'=>$own_answer_text
                            );
                            if($this->vote_radio_checkbox($votes)){
                                $success = true; 
                            }else{
                                $success = false;  
                            }
                        }
                        if($success){
                            echo $_GET['jsoncall'] . '(' . json_encode( array('result'=> true) ) . ');';
                        }else{
                            echo $_GET['jsoncall'] . '(' . json_encode( array('result'=> false) ) . ');';
                        }
                        break;
                }
            }
        }

        public function vote_radio_checkbox($votes){
            if($this->db->insert('votes', $votes)){
                $poll_over_limit = $this->db->get_where('poll', array('id'=> $_GET['poll_id']))->result();
                $limit = $poll_over_limit[0]->votes_left;
                $limit-=1;
                $this->db->where('id', $_GET['poll_id'])->update('poll', array('votes_left'=> $limit));
                return true;
            }else{
                return false;
            }            
        }
        public function vote_own_answer($votes){

        }

        public function citaj_rezultate(){ /* return:object (title, description, keywords) */
            return $this->db->get_where(' votes', array('poll_id'=> $_GET['poll_id']))->result();
        }
        public function anketa_status($id,$status){
            return $this->db->where('id', $id)->update('poll', array('status'=>$status));
        }

    }
?>
